import path from "path"
import fs from "fs"

/** @type {import('vite').Plugin} */
export default function viewHtmlPlugin(AGENCY_TOKEN_NAME) {
    const rootDir = path.resolve(__dirname, '../../');
    const viewPath = path.join(rootDir, 'view.html');
    const viteMainPath = path.join(rootDir, 'config/viteMain.js');
    const bingoStoreViewsPath = path.join(rootDir, 'english-view/src/views/bingostore');
    const commonViewsPath = path.join(rootDir, 'english-view/src/views/_common');

    return {
        name: 'view-html-plugin',
        configureServer(server) {
            server.middlewares.use(async (req, res, next) => {
                let url = req.url;

                // console.log({url})

                // 处理注入脚本
                if (url.includes("inject-env.js")) {
                    res.setHeader('Content-Type', 'application/javascript');
                    res.end(`
                    // 此文件流水线会自动注入，请勿修改
    export const INJECTED_CONFIG = {
      tokenName: "${AGENCY_TOKEN_NAME}",
    }
                    `);
                    return;
                }

                // 处理 _main.js 请求
                if (url.includes("english-view/src/views/bingostore/_main.js")) {
                    try {
                        const data = await fs.promises.readFile(viteMainPath, 'utf-8');
                        res.setHeader('Content-Type', 'application/javascript');
                        res.end(data);
                    } catch (err) {
                        res.statusCode = 500;
                        res.end('Internal Server Error');
                    }
                    return;
                }

                // URL 重定向
                if (url === "/") {
                    url = "/home/workbench?_t=1";
                }

                // 处理带 _t 参数的请求
                if (url.includes("?_t") && !url.includes("/user/login")) {
                    const [vuePath, query] = url.split("?");
                    
                    let scriptSrc = path.join('/english-view/src/views/bingostore', vuePath, 'main.js');
                    const vueMainFilePath = path.join(bingoStoreViewsPath, vuePath, 'main.js');

                    // 如果文件不存在，则跳过
                    if (!fs.existsSync(vueMainFilePath)) {
                        return next();
                    }

                    if (vuePath.includes("demo/")) {
                        scriptSrc = path.join('/english-view/src/views/_common', vuePath, 'main.js');
                    }

                    try {
                        let html = await fs.promises.readFile(viewPath, 'utf-8');
                        html = html.replace("__VUE_PATH__", scriptSrc);
                        res.setHeader('Content-Type', 'text/html');
                        res.end(html);
                    } catch (err) {
                        res.statusCode = 500;
                        res.end('Internal Server Error');
                    }
                    return;
                }

                next();
            });
        },
    };
}